package com.baoyang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baoyang.entity.BaoyangUser;
import com.baoyang.entity.Container;
import com.baoyang.entity.ProductName;
import com.baoyang.entity.vo.BatchSetArrivalStationReqVO;
import com.baoyang.entity.vo.DashboardRespVO;
import com.baoyang.entity.vo.ExportContainerByStatusReqVO;
import com.baoyang.entity.vo.ExportContainerReqVO;
import com.baoyang.entity.vo.MyTransportationCountRespVO;
import com.baoyang.entity.vo.PcUnloadCountRespVO;
import com.baoyang.entity.vo.ProductNameCountRespVO;
import com.baoyang.mapper.BaoyangUserMapper;
import com.baoyang.mapper.ContainerMapper;
import com.baoyang.mapper.ProductNameMapper;
import com.baoyang.service.IContainerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baoyang.tool.utils.SecurityUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 货柜信息表 服务实现类
 * </p>
 *
 * @author 金佳军
 * @since 2025-07-05
 */
@Service
public class ContainerServiceImpl extends ServiceImpl<ContainerMapper, Container> implements IContainerService {

    @Resource
    private ContainerMapper containerMapper;
    @Resource
    private ProductNameMapper productNameMapper;

    @Resource
    private BaoyangUserMapper baoyangUserMapper;

    @Override
    public IPage<Container> pageContainerList(Page<Container> page, String boxNo, Long productNameId, String shippingStation, String arrivalStation, String shipmentDate, Long driverId,
                                              Integer transportationStatus, Integer type, String dataScope) {
        String userId = SecurityUtils.getCurrentUserId();
        QueryWrapper<Container> queryWrapper = new QueryWrapper<>();
        if (boxNo != null && !boxNo.trim().isEmpty()) {
            queryWrapper.like("box_no", boxNo);
        }
        if (driverId != null) {
            queryWrapper.eq("driver_id", driverId);
        }
        if (productNameId != null) {
            queryWrapper.eq("product_name_id", productNameId);
        }
        if (shippingStation != null && !shippingStation.trim().isEmpty()) {
            queryWrapper.like("shipping_station", shippingStation);
        }
        if (arrivalStation != null && !arrivalStation.trim().isEmpty()) {
            queryWrapper.like("arrival_station", arrivalStation);
        }
        if (shipmentDate != null && !shipmentDate.trim().isEmpty()) {
            queryWrapper.eq("shipment_date", shipmentDate);
        }
        if (transportationStatus != null) {
            queryWrapper.eq("transportation_status", transportationStatus);
        }
        if (type != null) {
            queryWrapper.eq("type", type);
        }
        // 数据范围（1：全部数据权限,2：个人数据)
        if (dataScope.equals("2")) {
            queryWrapper.eq("create_by", userId);
        }
        queryWrapper.orderByDesc("create_time", "id", "box_no");
        Page<Container> containerPage = containerMapper.selectPage(page, queryWrapper);
        List<Container> records = containerPage.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            for (Container record : records) {
                record.setProjectName(productNameMapper.selectById(record.getProductNameId()).getName());
            }
            containerPage.setRecords(records);
        }
        return containerPage;
    }

    @Override
    public boolean addContainer(Container container) {
        container.setTransportationStatus(1);
        container.setType(1);
        return containerMapper.insert(container) > 0;
    }

    @Override
    public boolean setArrivalStation(Container container) {
        Container byId = containerMapper.selectById(container.getId());
        if (!byId.getTransportationStatus().equals(1)) {
            throw new RuntimeException("当前状态不能设置到站");
        }
        /* 设置截止日期,如果是下午八点前，当天算一天。八点后到站，今天不算第一天 */
        // 获取当前时间
        LocalTime currentTime = LocalTime.now();

        // 定义下午8点时间
        LocalTime eightPM = LocalTime.of(20, 0);

        // 比较时间
        LocalDate deadlineDate = null;
        if (currentTime.isBefore(eightPM)) {
            deadlineDate = LocalDate.now().plusDays(2);
        } else {
            deadlineDate = LocalDate.now().plusDays(3);
        }
        if (StringUtils.hasText(container.getContainerLot())) {
            byId.setContainerLot(container.getContainerLot());
        }
        byId.setDeadlineDate(deadlineDate);
        byId.setTransportationStatus(2);
        byId.setArrivalDate(LocalDate.now());
        return containerMapper.updateById(byId) > 0;
    }

    @Override
    public boolean commit(Container container) {
        String userId = SecurityUtils.getCurrentUserId();
        BaoyangUser baoyangUser = baoyangUserMapper.selectById(userId);
        List<Container> containerList = containerMapper.selectList(new QueryWrapper<Container>()
                .eq("driver_id", baoyangUser.getId())
                .eq("transportation_status", 3));

        if (!CollectionUtils.isEmpty(containerList)) {
            throw new RuntimeException("当前用户有正在运输的货柜，请勿重复提交");
        }
        Container byId = containerMapper.selectById(container.getId());
        if (!byId.getTransportationStatus().equals(2)) {
            throw new RuntimeException("当前状态不能提交");
        }
        byId.setDriverId(baoyangUser.getId());
        byId.setDriverName(baoyangUser.getNickName());
        byId.setTransportationStatus(3);
        return containerMapper.updateById(byId) > 0;
    }

    @Override
    public Container queryUserContainer(Long userId) {
        List<Container> containerList = containerMapper.selectList(new QueryWrapper<Container>()
                .eq("driver_id", userId)
                .eq("transportation_status", 3));
        if (CollectionUtils.isEmpty(containerList)) {
            return null;
        }
        if (containerList.size() > 1) {
            throw new RuntimeException("数据异常，用户有多个正在运输的货柜，请联系管理员进行操作");
        }
        Container container = containerList.get(0);
        container.setProjectName(productNameMapper.selectById(container.getProductNameId()).getName());
        return container;
    }

    @Override
    public boolean cancel(Container container) {
        Container byId = containerMapper.selectById(container.getId());
        if (!byId.getTransportationStatus().equals(3)) {
            throw new RuntimeException("当前状态不能撤销");
        }
        UpdateWrapper<Container> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("driver_id", null);
        updateWrapper.set("driver_name", null);
        updateWrapper.set("transportation_status", 2);
        updateWrapper.eq("id", byId.getId());
        return containerMapper.update(null, updateWrapper) > 0;
    }

    @Override
    public IPage<Container> getAllArrivedPage(Page<Container> page, Long projectNameId, Integer transportationStatus,
                                              String boxNo, String dataScope) {
        QueryWrapper<Container> queryWrapper = new QueryWrapper<>();
        if (projectNameId != null) {
            queryWrapper.eq("product_name_id", projectNameId);
        }
        if (transportationStatus != null) {
            queryWrapper.eq("transportation_status", transportationStatus);
        }
        if (boxNo != null && !boxNo.trim().isEmpty()) {
            queryWrapper.eq("box_no", boxNo);
        }
        // 1. 首先按type降序排列（type=3排最上面）
        queryWrapper.orderByDesc("type");

        // 2. 然后按deadline_date升序排列
        queryWrapper.orderByAsc("deadline_date");

        // 3. 再按container_lot排序（忽略第一位数字，从小到大）
        queryWrapper.orderByAsc("CASE WHEN container_lot IS NULL OR container_lot = '' THEN 999999 ELSE CAST(SUBSTRING(container_lot, 2) AS UNSIGNED) END");

        // 4. 最后按id排序，确保分页的唯一性和稳定性
        queryWrapper.orderByAsc("id");

        Page<Container> containerPage = containerMapper.selectPage(page, queryWrapper);
        List<Container> records = containerPage.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            List<Long> projectNameIds = records.stream().map(Container::getProductNameId).distinct()
                    .collect(Collectors.toList());
            List<ProductName> productNameList = productNameMapper
                    .selectList(new QueryWrapper<ProductName>().in("id", projectNameIds));
            Map<Long, String> productNameMap = productNameList.stream()
                    .collect(Collectors.toMap(ProductName::getId, ProductName::getName));
            for (Container record : records) {
                record.setProjectName(productNameMap.get(record.getProductNameId()));
            }
            containerPage.setRecords(records);
        }
        return containerPage;
    }

    @Override
    public DashboardRespVO dashboard() {
        DashboardRespVO dashboardRespVO = new DashboardRespVO();
        dashboardRespVO.setNotArrived(count(new QueryWrapper<Container>().eq("transportation_status", 1)));
        dashboardRespVO.setArrived(count(new QueryWrapper<Container>().eq("transportation_status", 2)));
        dashboardRespVO.setInTransport(count(new QueryWrapper<Container>().eq("transportation_status", 3)));
        dashboardRespVO.setUnloadToday(count(new QueryWrapper<Container>().eq("transportation_status", 4)
                .between("unloading_date", LocalDate.now(), LocalDate.now().plusDays(1))));
        return dashboardRespVO;
    }

    @Override
    public IPage<Container> dashboardList(Page<Container> page, Long projectNameId, Integer transportationStatus) {
        QueryWrapper<Container> queryWrapper = new QueryWrapper<>();
        if (projectNameId != null) {
            queryWrapper.eq("product_name_id", projectNameId);
        }
        queryWrapper.eq("transportation_status", transportationStatus);
        queryWrapper.orderByDesc("type");
        queryWrapper.orderByDesc("create_time", "id", "box_no");
        Page<Container> containerPage = containerMapper.selectPage(page, queryWrapper);
        List<Container> records = containerPage.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            List<Long> projectNameIds = records.stream().map(Container::getProductNameId).distinct()
                    .collect(Collectors.toList());
            List<ProductName> productNameList = productNameMapper
                    .selectList(new QueryWrapper<ProductName>().in("id", projectNameIds));
            Map<Long, String> productNameMap = productNameList.stream()
                    .collect(Collectors.toMap(ProductName::getId, ProductName::getName));
            for (Container record : records) {
                record.setProjectName(productNameMap.get(record.getProductNameId()));
            }
            containerPage.setRecords(records);
        }
        return containerPage;
    }

    @Override
    public IPage<Container> todayUnloadList(Page<Container> page, String driverName) {
        QueryWrapper<Container> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("transportation_status", 4);

        if (driverName != null && !driverName.trim().isEmpty()) {
            queryWrapper.like("driver_name", driverName);
        }
        queryWrapper.orderByDesc("unloading_date");
        return containerMapper.selectPage(page, queryWrapper);
    }

    @Override
    public boolean unload(Container container) {
        Container byId = containerMapper.selectById(container.getId());
        if (container.getUnloadPointId() == null){
            throw new RuntimeException("请选择卸货点");
        }
        byId.setUnloadPointId(container.getUnloadPointId());
        byId.setUnloadPoint(container.getUnloadPoint());
        byId.setUnloadingWeight(container.getUnloadingWeight());
        byId.setUnloadingDate(LocalDateTime.now());
        byId.setTransportationStatus(4);
        byId.setType(1);
        return updateById(byId);
    }

    @Override
    public IPage<Container> myTransportationPageList(Page<Container> page, String boxNo, String startTime,
                                                     String endTime) {
        QueryWrapper<Container> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("driver_id", SecurityUtils.getCurrentUserId());
        queryWrapper.eq("transportation_status", 4);
        if (boxNo != null && !boxNo.trim().isEmpty()) {
            queryWrapper.like("box_no", boxNo);
        }
        if (StringUtils.hasText(startTime) && StringUtils.hasText(endTime)) {
            queryWrapper.between("unloading_date", startTime, endTime);
        }
        queryWrapper.orderByDesc("unloading_date");
        Page<Container> containerPage = containerMapper.selectPage(page, queryWrapper);
        List<Container> records = containerPage.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            List<Long> projectNameIds = records.stream().map(Container::getProductNameId).distinct()
                    .collect(Collectors.toList());
            List<ProductName> productNameList = productNameMapper
                    .selectList(new QueryWrapper<ProductName>().in("id", projectNameIds));
            Map<Long, String> productNameMap = productNameList.stream()
                    .collect(Collectors.toMap(ProductName::getId, ProductName::getName));
            for (Container record : records) {
                record.setProjectName(productNameMap.get(record.getProductNameId()));
            }
            containerPage.setRecords(records);
        }
        return containerPage;
    }

    @Override
    public MyTransportationCountRespVO myTransportationCount() {
        MyTransportationCountRespVO myTransportationCountRespVO = new MyTransportationCountRespVO();
        myTransportationCountRespVO.setThisMonthTransportationCount(
                count(new QueryWrapper<Container>().eq("driver_id", SecurityUtils.getCurrentUserId()).eq(
                        "transportation_status", 4).between("unloading_date",
                        LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()),
                        LocalDate.now().with(TemporalAdjusters.lastDayOfMonth()))));
        return myTransportationCountRespVO;
    }

    @Override
    public IPage<Container> fishingBoxTrackingPageList(Page<Container> page, String boxNo, Long productNameId) {
        QueryWrapper<Container> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("transportation_status", 2);
        if (boxNo != null && !boxNo.trim().isEmpty()) {
            queryWrapper.like("box_no", boxNo);
        }
        if (productNameId != null) {
            queryWrapper.eq("product_name_id", productNameId);
        }
        queryWrapper.orderByDesc("type");
        queryWrapper.orderByDesc("deadline_date");
        Page<Container> containerPage = containerMapper.selectPage(page, queryWrapper);
        List<Container> records = containerPage.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            List<Long> productNameIds = records.stream().map(Container::getProductNameId).collect(Collectors.toList());
            List<ProductName> productNameList = productNameMapper
                    .selectList(new QueryWrapper<ProductName>().lambda().in(ProductName::getId, productNameIds));
            Map<Long, String> productNameMap = productNameList.stream()
                    .collect(Collectors.toMap(ProductName::getId, ProductName::getName));
            records.forEach(container -> container.setProjectName(productNameMap.get(container.getProductNameId())));
            containerPage.setRecords(records);
        }
        return containerPage;
    }

    @Override
    public IPage<ProductNameCountRespVO> productNameNotArrivedCount(Integer pageNum, Integer pageSize,
                                                                    Integer transportationStatus) {
        // 1. 创建分页对象
        Page<ProductNameCountRespVO> page = new Page<>(pageNum, pageSize);

        // 2. 构建查询条件
        QueryWrapper<Container> wrapper = new QueryWrapper<>();
        wrapper.eq("bc.transportation_status", transportationStatus)
                .eq("del_flag", "0");

        // 3. 执行自定义查询
        return containerMapper.selectContainerProductStats(page, wrapper);
    }

    @Override
    public IPage<Container> getUnloadedContainersByDriverIdPageList(Page<Container> page, String startTime,
                                                                    String endTime, String id) {
        QueryWrapper<Container> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("driver_id", id);
        queryWrapper.eq("transportation_status", 4);
        if (StringUtils.hasText(startTime) && StringUtils.hasText(endTime)) {
            queryWrapper.between("unloading_date", startTime, endTime);
        }
        queryWrapper.orderByDesc("unloading_date");
        Page<Container> containerPage = containerMapper.selectPage(page, queryWrapper);
        List<Container> records = containerPage.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            List<Long> productNameIds = records.stream().map(Container::getProductNameId).collect(Collectors.toList());
            List<ProductName> productNameList = productNameMapper
                    .selectList(new QueryWrapper<ProductName>().lambda().in(ProductName::getId, productNameIds));
            Map<Long, String> productNameMap = productNameList.stream()
                    .collect(Collectors.toMap(ProductName::getId, ProductName::getName));
            records.forEach(container -> container.setProjectName(productNameMap.get(container.getProductNameId())));
            containerPage.setRecords(records);
        }
        return containerPage;
    }

    @Override
    public List<PcUnloadCountRespVO> pcUnloadCount() {
        List<PcUnloadCountRespVO> respVOList = new ArrayList<>();

        // 获取当前日期
        LocalDate currentDate = LocalDate.now().plusDays(1);
        // 获取十五天前的日期
        LocalDate fifteenDaysAgo = currentDate.minusDays(14); // 包含今天，所以是14天前

        // 获取十五天内已卸货的货柜
        List<Container> containerList = containerMapper.selectList(
                new QueryWrapper<Container>()
                        .eq("transportation_status", 4)
                        .between("unloading_date", fifteenDaysAgo, currentDate));

        // 按日期分组统计
        Map<LocalDate, List<Container>> listMap = containerList.stream()
                .collect(Collectors.groupingBy(a->a.getUnloadingDate().toLocalDate()));

        // 生成十五天的数据，包括没有卸货的日期
        for (int i = 0; i < 15; i++) {
            LocalDate date = fifteenDaysAgo.plusDays(i);
            PcUnloadCountRespVO pcUnloadCountRespVO = new PcUnloadCountRespVO();
            pcUnloadCountRespVO.setDate(date.toString());

            // 获取该日期的卸货数量
            List<Container> containersForDate = listMap.get(date);
            if (containersForDate != null) {
                pcUnloadCountRespVO.setCount((long) containersForDate.size());
            } else {
                pcUnloadCountRespVO.setCount(0L);
            }

            respVOList.add(pcUnloadCountRespVO);
        }

        return respVOList;
    }

    @Override
    public IPage<Container> pcUnloadPageList(Page<Container> page) {
        QueryWrapper<Container> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("transportation_status", 4);
        queryWrapper.orderByDesc("unloading_date");
        Page<Container> containerPage = containerMapper.selectPage(page, queryWrapper);
        List<Container> records = containerPage.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            List<Long> productNameIds = records.stream().map(Container::getProductNameId).collect(Collectors.toList());
            List<ProductName> productNameList = productNameMapper
                    .selectList(new QueryWrapper<ProductName>().lambda().in(ProductName::getId, productNameIds));
            Map<Long, String> productNameMap = productNameList.stream()
                    .collect(Collectors.toMap(ProductName::getId, ProductName::getName));
            records.forEach(container -> container.setProjectName(productNameMap.get(container.getProductNameId())));
            containerPage.setRecords(records);
        }
        return containerPage;
    }

    @Override
    public boolean batchSetArrivalStation(List<BatchSetArrivalStationReqVO> reqVOS) {
        for (BatchSetArrivalStationReqVO reqVO : reqVOS) {
            Container container = new Container();
            container.setId(reqVO.getId());
            container.setContainerLot(reqVO.getContainerLot());
            setArrivalStation(container);
        }
        return true;
    }

    @Override
    public boolean editContainer(Container container) {
//        Container byId = containerMapper.selectById(container.getId());
//        if (StringUtils.hasText(container.getContainerLot()) && byId.getTransportationStatus().equals(1)) {
//            throw new RuntimeException("未到站货柜无法修改箱位");
//        }
//        byId.setBoxNo(container.getBoxNo());
//        byId.setProductNameId(container.getProductNameId());
//        byId.setArrivalStation(container.getArrivalStation());
//        byId.setShippingStation(container.getShippingStation());
//        byId.setLoadingWeight(container.getLoadingWeight());
//        byId.setContainerLot(container.getContainerLot());
//        byId.setShipmentDate(container.getShipmentDate());
        return containerMapper.updateById(container) > 0;
    }

    @Override
    @Transactional
    public boolean importByExcel(MultipartFile file) {
        try {
            XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
            XSSFSheet sheet = wb.getSheetAt(0);
            for (int i = 0; i <= sheet.getLastRowNum(); i++) {
                XSSFRow row = sheet.getRow(i);
                if (row != null) {
                    if (i == 0) {
                        // 校验表格头
                        if (!row.getCell(0).getStringCellValue().equals("箱号")
                                || !row.getCell(1).getStringCellValue().equals("货物品名")
                                || !row.getCell(2).getStringCellValue().equals("发货站")
                                || !row.getCell(3).getStringCellValue().equals("到达站")
                                || !row.getCell(4).getStringCellValue().equals("装车重量")
                                || !row.getCell(5).getStringCellValue().equals("发货日期")) {
                            wb.close();
                            throw new RuntimeException("模板表格头格式错误（箱号+货物品名+发货站+到达站+装车重量+发货日期）");
                        }
                    } else {
                        Container container = new Container();
                        container.setBoxNo(getCellValueAsString(row.getCell(0)));
                        container
                                .setProductNameId(
                                        productNameMapper
                                                .selectOne(new QueryWrapper<ProductName>().lambda()
                                                        .eq(ProductName::getName, getCellValueAsString(row.getCell(1))))
                                                .getId());
                        container.setShippingStation(getCellValueAsString(row.getCell(2)));
                        container.setArrivalStation(getCellValueAsString(row.getCell(3)));
                        container.setLoadingWeight(getCellValueAsString(row.getCell(4)));
                        // 处理日期
                        XSSFCell dateCell = row.getCell(5);
                        LocalDate shippingDate = getDateFromCell(dateCell);
                        container.setShipmentDate(shippingDate);
                        container.setTransportationStatus(1);
                        container.setType(1);
                        containerMapper.insert(container);
                    }
                }
            }
            wb.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    // 专门处理日期的方法
    private LocalDate getDateFromCell(XSSFCell cell) {
        if (cell == null) {
            return null;
        }

        if (cell.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell)) {
            Date date = cell.getDateCellValue();
            return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        }

        return null;
    }

    // 替换所有的 getStringCellValue() 调用
    private String getCellValueAsString(XSSFCell cell) {
        if (cell == null) {
            return "";
        }

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    Date date = cell.getDateCellValue();
                    LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                    return localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                } else {
                    // 使用BigDecimal的精确构造，避免浮点数精度问题
                    double numericValue = cell.getNumericCellValue();
                    BigDecimal bd = new BigDecimal(Double.toString(numericValue));
                    return bd.stripTrailingZeros().toPlainString();
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }

    @Override
    @Transactional(readOnly = true)
    public void exportContainerExcel(ExportContainerReqVO reqVO, HttpServletResponse response) {
        try {
            // 构建查询条件
            QueryWrapper<Container> queryWrapper = new QueryWrapper<>();

            // 根据卸货时间范围查询
            if (reqVO.getStartTime() != null && reqVO.getEndTime() != null) {
                queryWrapper.between("unloading_date", reqVO.getStartTime(), reqVO.getEndTime().plusDays(1));
            }

            // 根据司机ID列表查询
            if (reqVO.getDriverIds() != null && !reqVO.getDriverIds().isEmpty()) {
                queryWrapper.in("driver_id", reqVO.getDriverIds());
            }

            // 只查询已卸货的货柜
            queryWrapper.eq("transportation_status", 4); // 4表示已卸货状态

            // 按卸货时间排序
            queryWrapper.orderByAsc("unloading_date");

            // 查询数据
            List<Container> containerList = containerMapper.selectList(queryWrapper);
            // 填充货物品名信息
            for (Container container : containerList) {
                if (container.getProductNameId() != null) {
                    ProductName productName = productNameMapper.selectById(container.getProductNameId());
                    if (productName != null) {
                        container.setProjectName(productName.getName());
                    }
                }
            }

            // 创建Excel工作簿
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet = workbook.createSheet("货柜卸货记录");

            // 创建表头
            XSSFRow headerRow = sheet.createRow(0);
            String[] headers = {"日期", "车号", "品名", "箱号", "实收吨数", "驾驶员姓名","发货站","发货日期","到站日期"};

            for (int i = 0; i < headers.length; i++) {
                XSSFCell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 填充数据
            int rowNum = 1;
            for (Container container : containerList) {
                BaoyangUser baoyangUser = baoyangUserMapper.selectById(container.getDriverId());
                XSSFRow row = sheet.createRow(rowNum++);

                // 卸货日期
                if (container.getUnloadingDate() != null) {
                    row.createCell(0).setCellValue(
                            container.getUnloadingDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                }

                // 车号
                row.createCell(1).setCellValue(baoyangUser.getCarNumber() != null ? baoyangUser.getCarNumber() : "");

                // 品名
                row.createCell(2).setCellValue(container.getProjectName() != null ? container.getProjectName() : "");

                // 箱号
                row.createCell(3).setCellValue(container.getBoxNo());

                // 实收吨数（卸车重量）
                row.createCell(4)
                        .setCellValue(container.getUnloadingWeight() != null ? container.getUnloadingWeight() : "");

                // 驾驶员姓名
                row.createCell(5).setCellValue(baoyangUser.getNickName() != null ? baoyangUser.getNickName() : "");
                // 发货站
                row.createCell(6).setCellValue(container.getShippingStation() != null ? container.getShippingStation() : "");
                // 发货日期
                if (container.getShipmentDate() != null) {
                    row.createCell(7).setCellValue(
                            container.getShipmentDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                }
                // 到站日期
                if (container.getArrivalDate() != null) {
                    row.createCell(8).setCellValue(
                            container.getArrivalDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                }
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            // 设置文件名，使用英文避免编码问题，并添加时间戳
            String timestamp = java.time.LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
            String fileName = "container_unload_record_" + timestamp + ".xlsx";
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

            // 写入响应流
            workbook.write(response.getOutputStream());
            workbook.close();

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出Excel失败: " + e.getMessage());
        }
    }

    @Override
    public boolean batchDelete(List<String> ids) {
        if (ids != null && !ids.isEmpty()) {
            return containerMapper.deleteBatchIds(ids) > 0;
        }
        return false;
    }

    @Override
    @Transactional(readOnly = true)
    public void exportExcelByStatus(ExportContainerByStatusReqVO reqVO, HttpServletResponse response) {
        try {
            // 构建查询条件
            QueryWrapper<Container> queryWrapper = new QueryWrapper<>();

            // 根据发货时间范围查询
            if (reqVO.getStartTime() != null && reqVO.getEndTime() != null) {
                queryWrapper.between("shipment_date", reqVO.getStartTime(), reqVO.getEndTime());
            }

            // 根据司机ID列表查询
            if (CollectionUtils.isEmpty(reqVO.getTransportationStatusList())) {
                throw new RuntimeException("请选择要导出的状态");
            }
            queryWrapper.in("transportation_status", reqVO.getTransportationStatusList());

            queryWrapper.orderByAsc("shipment_date");

            // 查询数据
            List<Container> containerList = containerMapper.selectList(queryWrapper);
            // 填充货物品名信息
            for (Container container : containerList) {
                if (container.getProductNameId() != null) {
                    ProductName productName = productNameMapper.selectById(container.getProductNameId());
                    if (productName != null) {
                        container.setProjectName(productName.getName());
                    }
                }
            }

            // 创建Excel工作簿
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet = workbook.createSheet("货柜卸货记录");

            // 创建表头
            XSSFRow headerRow = sheet.createRow(0);
            String[] headers = {"箱号", "货物品名", "发货站", "到达站", "装车重量", "发货日期"};

            for (int i = 0; i < headers.length; i++) {
                XSSFCell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 填充数据
            int rowNum = 1;
            for (Container container : containerList) {
                XSSFRow row = sheet.createRow(rowNum++);

                // 箱号
                row.createCell(0).setCellValue(container.getBoxNo() != null ? container.getBoxNo() : "");

                // 货物品名
                row.createCell(1).setCellValue(container.getProjectName() != null ? container.getProjectName() : "");

                // 发货站
                row.createCell(2).setCellValue(container.getShippingStation() != null ? container.getShippingStation() : "");

                // 到达站
                row.createCell(3).setCellValue(container.getArrivalStation() != null ? container.getArrivalStation() : "");

                // 装车重量
                row.createCell(4).setCellValue(container.getLoadingWeight() != null ? container.getLoadingWeight() : "");

                // 发货日期
                if (container.getShipmentDate() != null) {
                    row.createCell(5).setCellValue(
                            container.getShipmentDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                }
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            // 设置文件名，使用英文避免编码问题，并添加时间戳
            String timestamp = java.time.LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
            String fileName = "container_unload_record_" + timestamp + ".xlsx";
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

            // 写入响应流
            workbook.write(response.getOutputStream());
            workbook.close();

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出Excel失败: " + e.getMessage());
        }
    }
}
